package com.zzyl.framework.interceptor;

import com.zzyl.common.constant.HttpStatus;
import com.zzyl.common.exception.base.BaseException;
import com.zzyl.common.utils.StringUtils;
import com.zzyl.common.utils.UserThreadLocal;
import com.zzyl.framework.web.service.TokenService;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jwts;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
@Component
public class MemberInterCeptor implements HandlerInterceptor {

    @Autowired
    private TokenService tokenService;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String token = request.getHeader("authorization");
        if (token == null || token.isEmpty()) {
            response.setStatus(HttpStatus.UNAUTHORIZED);
            throw new BaseException("认证失败");
        }
        try {
            Claims claims = tokenService.parseToken(token);
            if (claims == null){
                response.setStatus(HttpStatus.UNAUTHORIZED);
                throw new BaseException("认证失败");
            }
            Object userIdObj = claims.get("userId");
            Long userId = null;

            if (userIdObj instanceof Long) {
                userId = (Long) userIdObj;
            } else if (userIdObj instanceof Integer) {
                userId = ((Integer) userIdObj).longValue();
            } else if (userIdObj instanceof String) {
                try {
                    userId = Long.parseLong((String) userIdObj);
                } catch (NumberFormatException e) {
                    response.setStatus(HttpStatus.UNAUTHORIZED);
                    throw new BaseException("认证失败: userId格式错误");
                }
            } else if (userIdObj != null) {
                // 尝试转换其他数值类型
                userId = Long.valueOf(userIdObj.toString());
            }

            if (userId == null){
                response.setStatus(HttpStatus.UNAUTHORIZED);
                throw new BaseException("认证失败");
            }

            UserThreadLocal.set(userId);
            return true;
        } catch (Exception e) {
            e.printStackTrace();
            response.setStatus(HttpStatus.UNAUTHORIZED);
            throw new BaseException("认证失败: " + e.getMessage());
        }
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        UserThreadLocal.remove();
        HandlerInterceptor.super.afterCompletion(request, response, handler, ex);
    }
}
